package com.dd.keel.core.common.utils;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;

public class URLUtil {
	
	public static URL getURLFromClasspath(String fileName) throws Exception
	{
		URL url = fromResource(fileName, null);
		if(url==null){
			throw new Exception("No found "+fileName);
		}
		return url;
	}
	
	public static URL getURLFromClasspath(String fileName,Class contextClass) throws Exception
	{
		URL url = fromResource(fileName, (contextClass==null)?null:contextClass.getClassLoader() );
		if(url==null){
			throw new Exception("No found "+fileName);
		}
		return url;
	}
	
    public static URL fromResource(Class contextClass, String resourceName) {
        if (contextClass == null)
            return fromResource(resourceName, null);
        else
            return fromResource(resourceName, contextClass.getClassLoader());
    }

    public static URL fromResource(String resourceName, ClassLoader loader) {
        URL url = null;

        if (loader != null && url == null) url = loader.getResource(resourceName);
        if (loader != null && url == null) url = loader.getResource(resourceName + ".properties");

        if (loader == null && url == null) {
            try {
                loader = Thread.currentThread().getContextClassLoader();
            } catch (SecurityException e) {
                loader = URLUtil.class.getClass().getClassLoader();
            }
        }

        if (url == null) url = loader.getResource(resourceName);
        if (url == null) url = loader.getResource(resourceName + ".properties");

        if (url == null) url = ClassLoader.getSystemResource(resourceName);
        if (url == null) url = ClassLoader.getSystemResource(resourceName + ".properties");

        if (url == null) url = fromFilename(resourceName);
        if (url == null) url = fromUrlString(resourceName);
        
        if (url == null)
        {
        	String keel_home = EtcConfig.getKeelHomePath();
    		String file_path = keel_home + "etc/"+ resourceName;
        	url = fromFilename(file_path);
        }
        
        //LOGGER.log(LogService.LOG_DEBUG, "[fromResource] got URL " + (url == null ? "[NotFound]" : url.toExternalForm()) + " from resourceName " + resourceName );
        return url;
    }
	
    public static URL fromFilename(String filename) {
        if (filename == null) return null;
        File file = new File(filename);
        URL url = null;

        try {
            if (file.exists()) url = file.toURI().toURL();
        } catch (java.net.MalformedURLException e) {
            e.printStackTrace();
            url = null;
        }
        return url;
    }
    
    public static URL fromUrlString(String urlString) {
        URL url = null;       
        try {
            url = new URL(urlString);
        } catch (MalformedURLException e) {                        
        }
        
        return url;
    }
    
}
